package com.wd.tw.service;

import com.alibaba.fastjson2.JSONObject;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.wd.tw.config.AppConfig;
import com.wd.tw.domain.dto.request.ApiRequest;
import com.wd.tw.domain.dto.request.HeartBeatRequest;
import com.wd.tw.domain.dto.response.ApiResponse;
import com.wd.tw.domain.dto.response.RenewalResponse;
import com.wd.tw.utils.HttpUtils;
import com.wd.tw.websocket.client.CustomerClientService;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

import java.io.IOException;

import static com.wd.tw.constants.ApiConstant.HEART_BEAT_API;
import static com.wd.tw.constants.ApiConstant.TOKEN_RENEWAL;

/**
 * @className: HearBeatService
 * @description: TODO 类描述
 * @author: liumingkun
 * @date: 2024/11/4
 **/

@Service
@Slf4j
public class HeartBeatService {

    private final static Logger logger = LoggerFactory.getLogger(HeartBeatService.class);


    @Resource
    AppConfig appConfig;

    @Resource
    TokenService tokenService;

    @Resource
    CustomerClientService clientService;

    public void heartBeat() {
        if(tokenService.getToken()==null)
        {
            return;
        }
        ApiRequest<HeartBeatRequest> requestParam = new ApiRequest<>();

        String token = tokenService.getToken();
        requestParam.getBasic().setToken(token);

        HeartBeatRequest heartBeatRequest = new HeartBeatRequest();
        heartBeatRequest.setAllow_renewal(true);

        requestParam.setData(heartBeatRequest);

        logger.info("HeartBeat param:" + requestParam.toString());
        String result = HttpUtils.post(appConfig.getBaseApi() + HEART_BEAT_API, requestParam.toString());
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        ApiResponse<RenewalResponse> response = null;
        try {
            response = objectMapper.readValue(result, objectMapper.getTypeFactory().constructParametricType(ApiResponse.class, String.class));
            if(response.getBasic().getCode()!=200){
                logger.info("RefreshTokenByHeartBeat!");
                tokenService.refreshToken();
                //重新连接websocket
                clientService.reConnect();
            }
            logger.info("HeartBeat Result:" + JSONObject.toJSONString(response));
        } catch (IOException e) {
            e.printStackTrace();
        }


    }


    //续签token
    public void renewal() {
        if(tokenService.getToken()==null)
        {
            log.info("Token为空，不需要续签!");
            return;
        }
        ApiRequest requestParam = new ApiRequest();

        String token = tokenService.getToken();
        requestParam.getBasic().setToken(token);

        log.info("TOKEN续签参数:" + requestParam.toString());
        String result = HttpUtils.post(appConfig.getBaseApi() + TOKEN_RENEWAL, requestParam.toString());
        log.info("TOKEN续签结果:" + result);
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        ApiResponse<RenewalResponse> response = null;
        try {
            response = objectMapper.readValue(result, objectMapper.getTypeFactory().constructParametricType(ApiResponse.class, RenewalResponse.class));
            if(response.getBasic().getCode()!=200){
                logger.info("RefreshTokenByRenewal!");
                tokenService.refreshToken();
                //重新连接websocket
                clientService.reConnect();
            }
            else{
                tokenService.setToken(response.getData().getToken());
                tokenService.setRenewalTime(System.currentTimeMillis());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
